from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404, redirect

from feedbacks.models import Feedback
from main.models import Files
from .models import Message

@login_required
def message_list(request):

    msg_list = request.user.received_messages.all()
    return render(request, 'messagesite/list.html', {'msg_list': msg_list})

@login_required
def message_detail(request, pk):
    """读消息并标记已读"""
    msg = get_object_or_404(Message, pk=pk, recipient=request.user)
    msg.mark_read()
    return render(request, 'messagesite/detail.html', {'msg': msg})


def feedback_ajax(request, pk):
    file = get_object_or_404(Files, pk=pk)
    title = request.POST.get("title", "").strip()
    content = request.POST.get("content", "").strip()
    if not content:
        return JsonResponse({"status": "error", "msg": "内容不能为空！"})

    Feedback.objects.create(file=file, sender=request.user, title=title, content=content)

    # 邮件通知作者（可关）
    Message.objects.create(
        sender=request.user,
        recipient=file.author,
        title=f"文章反馈：{file.title}",
        content=f"用户 {request.user} 对您文章《{file.title}》的反馈：\n\n{content}"
    )
    return JsonResponse({"status": "ok", "msg": "反馈已发送！"})